﻿#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/asio.hpp>
#include "logs.h"
#include "VersionXml/VersionXml.h"
#include "HttpDownload.h"
#include "EasyZip/EasyUnZip.h"
#include <boost/program_options.hpp>
#include <boost/exception/diagnostic_information.hpp>

#include "Update.h"


#define APPNAME "AutoUpdate"  

#ifdef _DEBUG
#pragma comment(lib, "EasyZipd.lib")
#else
#pragma comment(lib, "EasyZip.lib")
#endif // _DEBUG

bool CreateDir(const boost::filesystem::path& path)
{
    if (boost::filesystem::exists(path))
    {
        if (!boost::filesystem::is_directory(path))
        {
            LOG_ERROR("tmp path is not dir %s", path.string().c_str());
            return false;
        }
        return true;
    }
    if (!boost::filesystem::create_directory(path))
    {
        LOG_ERROR("create dir error! %s", path.string().c_str());
        return false;
    }
    return true;
}

int main(int argc, char *argv[])
{
    int level{ 0 };
    std::string urlRemote{};
    std::string tmpPath{};
    //std::string xmlPath{};
    std::string outPath{};

    boost::program_options::options_description od("Options");
    od.add_options()
        ("help,h", "produce help message")
        (",u", boost::program_options::value<std::string>(&urlRemote), "server url")
        (",t", boost::program_options::value<std::string>(&tmpPath), "temporary directory path")
        // ("xml,x", boost::program_options::value<std::string>(&xmlPath), "version xml path")
        (",p", boost::program_options::value<std::string>(&outPath), "update path");

    boost::program_options::variables_map vm;
    try 
    {
        boost::program_options::store(boost::program_options::parse_command_line(argc, argv, od), vm);
        boost::program_options::notify(vm);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
        //std::cerr << boost::diagnostic_information(e) << std::endl;
        std::cout << od << std::endl;
        return -1;
    }

    if (urlRemote.empty() || vm.count("help"))
    {
        std::cout << od << std::endl;
        return -1;
    }
    if (tmpPath.empty())
    {
        tmpPath = "tmp/";
    }
    boost::filesystem::path exec{ argv[0] };
    boost::filesystem::path tmp{ tmpPath };
    boost::filesystem::path out{ outPath };
    if (tmp.is_relative())
    {
        tmp = exec.parent_path() / tmp;
    }
    if (out.is_relative())
    {
        out = exec.parent_path() / out;
    }
    if (!CreateDir(tmp))
    {
        return -1;
    }
    if (!CreateDir(out))
    {
        return -1;
    }
    Update up;
    int ret = up.AutoUpdate(urlRemote, out.string(), tmp.string());
    if (UPDATE_ERROR == ret)
    {
        return -1;
    }
    LOG_INFO("update complete!");
    return 0;
}
